package com.joven.security.service.impl;

import com.alibaba.fastjson.JSON;
import com.joven.security.dao.SysUserDao;
import com.joven.security.model.LoginUser;
import com.joven.security.model.SysUser;
import com.joven.security.service.UserService;
import com.joven.security.utils.JwtUtils;
import com.joven.security.utils.RedisUtils;
import com.joven.security.utils.ResultData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author wzj
 * @Date 2023-03-01 15:43
 **/
@Slf4j
@Service
public class UserServiceImpl implements UserService {
    public static final String LOGIN_FLAG = "loginUser:";

    @Resource
    private SysUserDao sysUserDao;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public ResultData queryByUserName(String userName) {
        if (StringUtils.isEmpty(userName)) {
            return ResultData.fail("userName不能为空！");
        }
        SysUser sysUser = sysUserDao.selectByUserName(userName);
        log.info("根据userName:{}查询到结果为：{}", userName, JSON.toJSONString(sysUser));
        return ResultData.success(sysUser);
    }

    @Override
    public ResultData login(SysUser sysUser) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(sysUser.getUserName(), sysUser.getPassword());
        //查询用户是否存在且密码是否合法
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        if (authentication == null) {
            return ResultData.fail("登陆失败！");
        }
        //认证通过，获取用户信息
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long id = loginUser.getSysUser().getId();
        if (id != null) {
            //生成jwt token返回前端，同时将用户信息存入redis
            String token = jwtUtils.generateToken(id);
            Map<String, String> maps = new HashMap<>();
            maps.put("token", token);
            redisUtils.set(LOGIN_FLAG + id, loginUser);
            return ResultData.success(maps);
        }
        return ResultData.fail("获取token失败");
    }

    @Override
    public ResultData logOut() {
        //若用户未登录执行登出操作，在TokenFilterComponent拦截器中会被拦截，认证会不通过
        //从SecurityContextHolder获取用户信息，能执行登出操作，说明该用户已登录且通过认证
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long id = loginUser.getSysUser().getId();
        if (id != null) {
            redisUtils.del(LOGIN_FLAG + id);
        }
        return ResultData.success();
    }
}
